package com.sam.im.heiqun.uis.activities;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialcamera.internal.PlayNewActivity;
import com.bumptech.glide.Glide;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.CircleItemEntity;
import com.sam.im.heiqun.entities.CommontsEntity;
import com.sam.im.heiqun.entities.FeedPraisesEntity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.entities.beans.ImageInfoBean;
import com.sam.im.heiqun.mvp.modle.ActionItem;
import com.sam.im.heiqun.mvp.modle.PhotoInfo;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.holder.ImageViewHolder;
import com.sam.im.heiqun.utils.KeyBoardUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.sam.im.heiqun.widgets.CommentListView;
import com.sam.im.heiqun.widgets.ExpandTextView;
import com.sam.im.heiqun.widgets.MultiImageView;
import com.sam.im.heiqun.widgets.PraiseListView;
import com.sam.im.heiqun.widgets.SnsPopupWindow;
import com.melink.bqmmsdk.widget.BQMMEditView;
import com.melink.bqmmsdk.widget.BQMMSendButton;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.TimeUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import com.sam.im.heiqun.utils.StringUtils;

public class CirclealldetailActivity extends BaseSwipeBackActivity {


    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.mess_et)
    BQMMEditView messEt;
    @BindView(R.id.emoji)
    ImageView emoji;
    @BindView(R.id.send_btn)
    BQMMSendButton sendBtn;
    @BindView(R.id.headIv)
    ImageView headIv;
    @BindView(R.id.nameTv)
    TextView nameTv;
    @BindView(R.id.urlTipTv)
    TextView urlTipTv;
    @BindView(R.id.contentTv)
    ExpandTextView contentTv;
    @BindView(R.id.multiImagView)
    MultiImageView multiImagView;
    @BindView(R.id.timeTv)
    TextView timeTv;
    @BindView(R.id.deleteBtn)
    TextView deleteBtn;
    @BindView(R.id.snsBtn)
    ImageView snsBtn;
    @BindView(R.id.linear1)
    LinearLayout linear1;
    @BindView(R.id.praiseListView)
    PraiseListView praiseListView;
    @BindView(R.id.commentList)
    CommentListView commentList;
    @BindView(R.id.digCommentBody)
    LinearLayout digCommentBody;
    @BindView(R.id.image_startvideo)
    ImageView image_startvideo ;
    public SnsPopupWindow snsPopupWindow;
    private PGService mPgService;
    private CircleItemEntity circleItem ;
    private  int commentType = 0 ; //  0  普通评论   1  回复别人
    private String replayId;
    private String feedid;
    @Override
    public int getContentViewId() {
        return R.layout.activity_circlealldetail;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.detal);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        feedid = getIntent().getStringExtra("feedid");
        Log.i("info","feedid=="+feedid);
        snsPopupWindow = new SnsPopupWindow(this);
        snsPopupWindow.setmItemClickListener(new SnsPopupWindow.OnItemClickListener() {
            @Override
            public void onItemClick(ActionItem item, int position) {
                switch (position){
                    case 0:
                        if (item.mTitle.toString().equals(getResources().getString(R.string.zan))){//赞
                            mPgService.getparise(ToolsUtils.getMyUserId(),feedid).subscribe(new AbsAPICallback<ValidateEntivity>() {
                                @Override
                                protected void onResultError(ApiException ex) {
                                }

                                @Override
                                public void onNext(ValidateEntivity validateEntivity) {
                                    if (validateEntivity != null) {
                                        ToolsUtils.showToast(CirclealldetailActivity.this,validateEntivity.getInfo());
                                        getData(feedid);
                                    }
                                }
                            });
                        }else {//取消
                            mPgService.delparise(feedid,ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
                                @Override
                                protected void onResultError(ApiException ex) {
                                    Toast.makeText(CirclealldetailActivity.this,getResources().getString(R.string.caozuo_fail),Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onNext(ValidateEntivity validateEntivity) {
                                    if (validateEntivity != null) {
                                        ToolsUtils.showToast(CirclealldetailActivity.this,validateEntivity.getInfo());
                                        getData(feedid);
                                    }
                                }
                            });
                        }
                        //showToast("0");
                        break;
                    case 1:
                        KeyBoardUtils.showKeyBoard(CirclealldetailActivity.this,messEt);
                        break;
                }
            }
        });
        mPgService = PGService.getInstance();
        getData(feedid);
    }
    private void getData(String feedid) {
        showProgress(getResources().getString(R.string.now_get));
        messEt.setText("");
        KeyBoardUtils.hideKeyBoard(this,messEt);
        mPgService.getonecircle(feedid, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<CircleItemEntity>() {
            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                ToolsUtils.showToast(CirclealldetailActivity.this, getResources().getString(R.string.circle_delete_o));
                finish();
            }
            @Override
            public void onNext(CircleItemEntity circleItemEntity) {

                if (circleItemEntity != null) {
                    circleItem = circleItemEntity ;
                    String createTime = circleItemEntity.getCreateTime();
                    String feedimg = circleItemEntity.getFeedImgs();
                    String feedText = circleItemEntity.getFeedText();
                    final List<CommontsEntity> imFeedComments = circleItemEntity.getImFeedComments();
                    List<FeedPraisesEntity> imFeedPraises = circleItemEntity.getImFeedPraises();
                    String userHeadUrl = circleItemEntity.getUserHeadUrl();
                    String userName = circleItemEntity.getUserName();
//                    circleItemEntity.getUserId()
                    Glide.with(CirclealldetailActivity.this).load(userHeadUrl).centerCrop().dontAnimate().error(R.drawable.head_defaul).into(headIv);
                    nameTv.setText(userName);
                    long l = Long.parseLong(createTime);
                    String recentlyTime = TimeUtil.getRecentlyTime(l);
                    timeTv.setText(recentlyTime);
                    contentTv.setText(feedText);
                    if(ToolsUtils.getMyUserId().equals(circleItemEntity.getUserId())){
                        deleteBtn.setVisibility(View.VISIBLE);
                        deleteBtn.setEnabled(true);
                    }else{
                        deleteBtn.setEnabled(false);
                        deleteBtn.setVisibility(View.GONE);
                    }
                    //判断是否已点赞
                    boolean ispraise = false;
                    if (imFeedPraises.size() > 0) {
                        for (int i = 0; i < imFeedPraises.size(); i++) {
                            FeedPraisesEntity imFeedPraisesBean = imFeedPraises.get(i);
                            String userId1 = imFeedPraisesBean.getUserId();//点赞人的id  这里暂不取消赞 如果已经有赞就不能再次赞了
                            if (userId1.equals(ToolsUtils.getMyUserId())) {
                                ispraise = true;
                                break;
                            }
                        }
                    }
                    if (ispraise) {//已经赞了
                        snsPopupWindow.getmActionItems().get(0).mTitle = getResources().getString(R.string.cancel);
                    } else {
                        snsPopupWindow.getmActionItems().get(0).mTitle = getResources().getString(R.string.zan);
                    }

                    final List<PhotoInfo> photos = new ArrayList<>();

                    int thisCircleType = 0 ;//0-文字图片；1-视频；2-URL

                    if (circleItemEntity.getFeedVideo().length() > 0 && feedimg.length() > 0){
                        thisCircleType = 1 ;
                    }else {
                        thisCircleType = 0 ;
                    }
                    try {
                        image_startvideo.setVisibility(View.GONE);
                    }catch (Exception e){
                        e.printStackTrace();
                    }


                    switch (thisCircleType){
                        case 0 ://文字图片
                            if (!StringUtils.isEmpty(feedimg)) {
                                if (feedimg.contains(",")){
                                    String[] splitimg = feedimg.split(",");
                                    for (int e = 0; e < splitimg.length;e++){
                                        PhotoInfo photoInfo = new PhotoInfo();
                                        photoInfo.url = splitimg[e];
                                        photos.add(photoInfo);
                                    }
                                }else {
                                    PhotoInfo photoInfo = new PhotoInfo();
                                    photoInfo.url = feedimg;
                                    photos.add(photoInfo);
                                }
                                if (photos != null && photos.size() > 0) {
                                    multiImagView.setVisibility(View.VISIBLE);
                                    multiImagView.setList(photos);
                                    multiImagView.setOnItemClickListener(new MultiImageView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(View view, int position) {
                                            //imagesize是作为loading时的图片size
                                            ImagePagerActivity.ImageSize imageSize = new ImagePagerActivity.ImageSize(view.getMeasuredWidth(), view.getMeasuredHeight());
                                            List<ImageInfoBean> photoUrls = new ArrayList<>();
                                            for (PhotoInfo photoInfo : photos) {
                                                photoUrls.add(new ImageInfoBean(photoInfo.url,true));
                                            }
                                            ImagePagerActivity.startImagePagerActivity(CirclealldetailActivity.this, photoUrls, position, imageSize);
                                        }
                                    });
                                } else {
                                    photos.clear();
                                    multiImagView.setVisibility(View.VISIBLE);
                                    multiImagView.setList(photos);
                                }
                            }else {
                                multiImagView.setVisibility(View.GONE);
                            }
                            break;
                        case 1 ://视频

                            if (!StringUtils.isEmpty(feedimg)) {

                                    PhotoInfo photoInfo = new PhotoInfo();
                                    photoInfo.url = feedimg;
                                    photos.add(photoInfo);

                                if (photos != null && photos.size() > 0) {
                                    multiImagView.setVisibility(View.VISIBLE);
                                    multiImagView.setList(photos);
                                    multiImagView.setOnItemClickListener(new MultiImageView.OnItemClickListener() {
                                        @Override
                                        public void onItemClick(View view, int position) {
                                            Intent intent = new Intent(CirclealldetailActivity.this, PlayNewActivity.class);
                                            intent.putExtra("videoUrl", circleItem.getFeedVideo());
                                            startActivity(intent);
                                        }
                                    });
                                } else {
                                    photos.clear();
                                    multiImagView.setVisibility(View.VISIBLE);
                                    multiImagView.setList(photos);
                                }
                                image_startvideo.setVisibility(View.VISIBLE);
                            }else {
                                multiImagView.setVisibility(View.GONE);
                                image_startvideo.setVisibility(View.GONE);
                            }

                            break;
                        case 2 ://URL
                            break;
                    }


                    //有点赞或者有评论
                    if (imFeedComments.size() > 0 || imFeedPraises.size() > 0) {
                        if (imFeedPraises.size() > 0) {//处理点赞列表
                            praiseListView.setOnItemClickListener(new PraiseListView.OnItemClickListener() {
                                @Override
                                public void onClick(int position) {
                                    // String userName = favortDatas.get(position).getUser().getName();
                                    // String userId = favortDatas.get(position).getUser().getId();
                                    // Toast.makeText(App.getInstance().getApplicationContext(), userName + " &id = " + userId, Toast.LENGTH_SHORT).show();
                                }
                            });
                            praiseListView.setDatas(imFeedPraises);
                            praiseListView.setVisibility(View.VISIBLE);
                        } else {
                            praiseListView.setVisibility(View.GONE);
                        }
                        if (imFeedComments.size() > 0) {//处理评论列表
                            commentList.setOnItemClickListener(new CommentListView.OnItemClickListener() {
                                @Override
                                public void onItemClick(int commentPosition) {
                                    // CommentItem commentItem = commentsDatas.get(commentPosition);
                                    String userId = imFeedComments.get(commentPosition).getUserId();
                                    if (userId.equals(ToolsUtils.getMyUserId())) {//这里的回复是自己的
                                       // Toast.makeText(context, "此条为您本人的回复", Toast.LENGTH_SHORT).show();
                                        // CommentDialog dialog = new CommentDialog(context, presenter, listBean, circlePosition);
                                        //   dialog.show();
                                    } else {//回复别人的评论
                                        commentType = 1 ;
                                        replayId = userId;
                                        KeyBoardUtils.showKeyBoard(CirclealldetailActivity.this,messEt);
                                    }
                                }
                            });
                            commentList.setOnItemLongClickListener(new CommentListView.OnItemLongClickListener() {
                                @Override
                                public void onItemLongClick(int commentPosition) {
                                    //长按进行复制或者删除
                                    //  CommentItem commentItem = commentsDatas.get(commentPosition);
                                    //  CommentDialog dialog = new CommentDialog(context, presenter, commentItem, circlePosition);
                                    // dialog.show();
                                }
                            });
                            commentList.setDatas(imFeedComments);
                            commentList.setVisibility(View.VISIBLE);

                        } else {
                            commentList.setVisibility(View.GONE);
                        }
                        digCommentBody.setVisibility(View.VISIBLE);
                    } else {
                        digCommentBody.setVisibility(View.GONE);
                    }
                }
                hideProgress();
            }
        });
    }

    @OnClick({R.id.pre_v_back, R.id.emoji, R.id.send_btn, R.id.headIv, R.id.nameTv, R.id.deleteBtn, R.id.snsBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.pre_v_back:
                finish();
                break;
            case R.id.emoji:
                break;
            case R.id.send_btn:
                String s = messEt.getText().toString();
                if (StringUtils.isEmpty(s)){
                    ToolsUtils.showToast(this,getResources().getString(R.string.pl_content_nonull));
                }else {
                    String replyid = "";
                    if (commentType==1){//如果是回复类型才传replyid
                        replyid = replayId;
                    }
                    PGService.getInstance().getconmment(ToolsUtils.getMyUserId(),replyid,circleItem.getFeedId(), s).subscribe(new AbsAPICallback<ValidateEntivity>() {
                        @Override
                        protected void onResultError(ApiException ex) {

                        }
                        @Override
                        public void onNext(ValidateEntivity validateEntivity) {
                            if (validateEntivity != null) {
                                ToolsUtils.showToast(CirclealldetailActivity.this,validateEntivity.getInfo());
                                commentType = 0 ;
                                KeyBoardUtils.hideKeyBoard(CirclealldetailActivity.this,messEt);
                                getData(feedid);
                            }
                        }
                    });

                }

                break;
            case R.id.headIv:
            case R.id.nameTv:
                Intent intent = new Intent(this, FriendDetailActivity.class);
                intent.putExtra("type", 1);
                Log.i("wgdinfo", "onViewClicked: -------------circleItem.getUserId()="+circleItem.getUserId());
                intent.putExtra("id", Long.parseLong(circleItem.getUserId()));
                startActivity(intent);
                break;
            case R.id.deleteBtn:
                dialog(circleItem.getFeedId());
                break;
            case R.id.snsBtn:
                snsPopupWindow.showPopupWindow(snsBtn);
                break;
        }
    }
    protected void dialog(final  String circleId) {
        AlertDialog.Builder builder = new AlertDialog.Builder(CirclealldetailActivity.this);
        builder.setMessage(getResources().getString(R.string.delete_ok));
        builder.setTitle(getResources().getString(R.string.tip));
        builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mPgService.deletecircle(circleId,ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
                    @Override
                    protected void onResultError(ApiException ex) {

                    }

                    @Override
                    public void onNext(ValidateEntivity validateEntivity) {
                        if (validateEntivity != null) {
                            ToolsUtils.showToast(CirclealldetailActivity.this,validateEntivity.getInfo());
                            EventBus.getDefault().post(circleId);
                            finish();
                        }
                    }
                });

            }
        });
        builder.setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }
}
